package com.server.gateway.handler;

import com.server.common.code.utils.ResultUtil;
import com.server.gateway.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.cloud.gateway.support.TimeoutException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 网关异常处理
 * @author LXC
 * @date 2022/4/30 10:21
 */
@Order(-1)
@Configuration
@Slf4j
public class MyErrorWebHandler implements ErrorWebExceptionHandler {

    @Resource
    private MessageUtils messageUtils;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());
        if(ex instanceof  NotFoundException){
            return messageUtils.sendResponse(exchange, ResultUtil.error("找不到服务"));
        }
        else if (ex instanceof ResponseStatusException) {
            return messageUtils.sendResponse(exchange, ResultUtil.error("响应状态异常"));
        }
        else if(ex instanceof TimeoutException){
            return messageUtils.sendResponse(exchange, ResultUtil.error("接口超时."));
        }
        return messageUtils.sendResponse(exchange, ResultUtil.error("内部服务错误"));
    }
}
